<template>
  <div class="orders-container">
    <div class="header">
      <h1>再生道订单管理系统</h1>
      <p class="slogan">高效管理，一目了然</p>
    </div>
    
    <div class="orders-box">
      <div class="filter-section">
        <h3><i class="el-icon-search"></i> 订单筛选</h3>
        <div class="filter-options">
          <el-button 
            type="primary"
            size="small"
            icon="el-icon-refresh"
            @click="fetchOrders"
            :loading="loading"
          >刷新订单</el-button>
        </div>
      </div>

      <!-- 订单状态选项卡 -->
      <el-tabs v-model="activeTab" @tab-click="handleTabClick">
        <el-tab-pane label="全部订单" name="all"></el-tab-pane>
        <el-tab-pane label="待接单" name="1"></el-tab-pane>
        <el-tab-pane label="已接单" name="2"></el-tab-pane>
        <el-tab-pane label="已完成" name="3"></el-tab-pane>
        <el-tab-pane label="待评价" name="4"></el-tab-pane>
        <el-tab-pane label="已取消" name="5"></el-tab-pane>
        <el-tab-pane label="取件中" name="6"></el-tab-pane>
      </el-tabs>

      <div class="orders-section">
        <h3>
          <i class="el-icon-s-order"></i> 
          {{ getStatusTitle(activeTab) }}
          <span class="order-count">(共 {{ total }} 个订单)</span>
        </h3>
        
        <div class="order-list" v-loading="loading">
          <template v-if="filteredOrders.length > 0">
            <el-card v-for="order in filteredOrders" 
                    :key="order.recyclingOrderNum" 
                    class="order-card"
                    :shadow="'hover'"
            >
              <div class="order-header">
                <span class="order-num">订单号：{{ order.recyclingOrderNum }}</span>
                <el-tag :type="getStatusType(order.status)">{{ getStatusText(order.status) }}</el-tag>
              </div>
              
              <div class="order-content">
                <div class="order-info">
                  <p>
                    <i class="el-icon-date"></i> 
                    创建时间：{{ formatTime(order.createdAt) }}
                  </p>
                  <p v-if="order.appointmentTime">
                    <i class="el-icon-time"></i> 
                    预约时间：{{ formatTime(order.appointmentTime) }}
                  </p>
                  <p v-if="order.appointPhone">
                    <i class="el-icon-mobile-phone"></i> 
                    联系电话：{{ order.appointPhone }}
                  </p>
                  <p>
                    <i class="el-icon-location"></i> 
                    回收地址：{{ formatAddress(order) }}
                  </p>
                  <p v-if="order.remarks">
                    <i class="el-icon-document"></i> 
                    备注信息：{{ order.remarks }}
                  </p>
                  <p v-if="order.stationName">
                    <i class="el-icon-office-building"></i> 
                    回收站：{{ order.stationName }}
                  </p>
                </div>
                
                <div class="order-actions">
                  <el-button 
                                        type="primary" 
                                        size="small"
                                        icon="el-icon-chat-dot-round"
                                        @click="chatWithCustomer(order.recyclingOrderNum)"
                                        :loading="chatLoading === order.recyclingOrderNum"
                                    >联系客户</el-button>
                  <!-- <el-button 
                    type="primary" 
                    size="small"
                    icon="el-icon-view"
                    @click="viewOrderDetail(order.recyclingOrderNum)"
                  >查看详情</el-button> -->
                </div>
              </div>
            </el-card>
          </template>
          
          <div v-else class="empty-orders">
            <i class="el-icon-tickets"></i>
            <p>暂无{{ getStatusText(activeTab) }}订单</p>
          </div>
          
          <!-- 分页控件 -->
          <el-pagination
            v-if="total > 0"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="pageNum"
            :page-sizes="[5, 10, 20, 50]"
            :page-size="pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total">
          </el-pagination>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  name: 'AllOrders',
  data() {
    return {
      orders: [],
      loading: false,
      refreshTimer: null,
      activeTab: 'all',
      pageNum: 1,
      pageSize: 10,
      total: 0
    }
  },
  computed: {
    filteredOrders() {
      if (this.activeTab === 'all') {
        return this.orders;
      } else {
        return this.orders.filter(order => order.status.toString() === this.activeTab);
      }
    }
  },
  
  mounted() {
    this.fetchOrders();
    
    // 每60秒自动刷新一次订单
    this.refreshTimer = setInterval(this.fetchOrders, 60000);
  },
  beforeDestroy() {
    if (this.refreshTimer) {
      clearInterval(this.refreshTimer);
    }
  },
  methods: {
            // 与客户聊天
            async chatWithCustomer(orderNum) {
            this.chatLoading = orderNum
            try {
                localStorage.setItem('currentChatOrder', orderNum)
                this.$router.push({
                    path: '/service/chat',
                    query: { orderNum }
                })
            } catch (error) {
                console.error('进入聊天错误:', error)
                this.$message.error('进入聊天失败，请重试')
            } finally {
                this.chatLoading = null
            }
        },
    // 获取订单列表
    async fetchOrders() {
      this.loading = true;
      try {
        const response = await this.$http.post('/recycle/recyclingOrder/selectOrderByCondition', {
          pageNum: this.pageNum,
          pageSize: this.pageSize
        });
        
        if (response.data.code === 200) {
          this.orders = response.data.data.list;
          this.total = response.data.data.total;
          this.pageNum = response.data.data.pageNum;
        } else {
          this.$message.error(response.data.message || '获取订单失败');
        }
      } catch (error) {
        console.error('获取订单错误:', error);
        this.$message.error('获取订单失败');
      } finally {
        this.loading = false;
      }
    },
    
    // 查看订单详情
    viewOrderDetail(orderNum) {
      this.$router.push({
        path: '/platform/order-detail',
        query: { orderNum }
      });
    },
    
    // 格式化时间
    formatTime(time) {
      if (!time) return '未设置';
      return new Date(time).toLocaleString();
    },
    
    // 格式化地址
    formatAddress(order) {
      return [order.city, order.district, order.street]
        .filter(Boolean)
        .join(' ');
    },
    
    // 获取订单状态文本
    getStatusText(status) {
      const statusMap = {
        '1': '待接单',
        '2': '已接单',
        '3': '已取消',
        '4': '待评价',
        '5': '已评价',
        '6': '取件中',
        'all': '全部'
      };
      return statusMap[status] || '未知状态';
    },
    
    // 获取订单状态标签类型
    getStatusType(status) {
      const typeMap = {
        '1': 'warning',
        '2': 'primary',
        '3': 'success',
        '4': 'warning',
        '5': 'info',
        '6': 'warning'
      };
      return typeMap[status] || 'info';
    },
    
    // 获取标题
    getStatusTitle(status) {
      if (status === 'all') return '全部订单';
      return this.getStatusText(status) + '订单';
    },
    
    // 处理标签页切换
    handleTabClick() {
      this.pageNum = 1;
      this.fetchOrders();
    },
    
    // 处理每页显示数量变化
    handleSizeChange(val) {
      this.pageSize = val;
      this.fetchOrders();
    },
    
    // 处理页码变化
    handleCurrentChange(val) {
      this.pageNum = val;
      this.fetchOrders();
    }
  }
}
</script>

<style scoped>
.orders-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
  min-height: 100vh;
  background-color: #f0f9eb;
}

.header {
  text-align: center;
  margin-bottom: 30px;
  padding: 20px 0;
}

.header h1 {
  color: #67c23a;
  font-size: 2.5em;
  margin-bottom: 10px;
}

.slogan {
  color: #606266;
  font-size: 1.2em;
  font-style: italic;
}

.orders-box {
  background: white;
  border-radius: 15px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
  padding: 30px;
}

.filter-section {
  margin-bottom: 20px;
  padding-bottom: 20px;
  border-bottom: 2px solid #f0f9eb;
}

.filter-options {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 16px;
  color: #303133;
}

.order-card {
  margin-bottom: 20px;
}

.order-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
  padding-bottom: 10px;
  border-bottom: 1px solid #ebeef5;
}

.order-num {
  font-weight: bold;
  color: #303133;
}

.order-content {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
}

.order-info {
  flex: 1;
}

.order-info p {
  margin: 8px 0;
  color: #606266;
}

.order-info i {
  margin-right: 8px;
  color: #67c23a;
}

.order-actions {
  display: flex;
  flex-direction: column;
  gap: 10px;
  min-width: 120px;
}

.empty-orders {
  text-align: center;
  padding: 40px 0;
  color: #909399;
}

.empty-orders i {
  font-size: 48px;
  margin-bottom: 10px;
}

h3 {
  color: #67c23a;
  margin-bottom: 15px;
  display: flex;
  align-items: center;
  gap: 8px;
}

h3 i {
  font-size: 1.2em;
}

.order-count {
  font-size: 0.8em;
  color: #909399;
  margin-left: 8px;
}

.el-pagination {
  text-align: center;
  margin-top: 30px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .orders-container {
    padding: 10px;
  }

  .header h1 {
    font-size: 2em;
  }

  .orders-box {
    padding: 15px;
  }

  .order-content {
    flex-direction: column;
  }

  .order-actions {
    margin-top: 15px;
    width: 100%;
    flex-direction: row;
    flex-wrap: wrap;
    justify-content: flex-end;
  }
}
</style> 